import * as d3 from 'd3';

export class RadarChart {
    constructor(container) {
        this.container = container;
        this.margin = { top: 50, right: 90, bottom: 20, left: 20 };
        
        this.width = 300;  
        this.height = 300; 
        this.radius = Math.min(this.width, this.height) / 2.5;
        
        this.svg = d3.select(container)
            .append('svg')
            .attr('width', this.width + this.margin.left + this.margin.right)
            .attr('height', this.height + this.margin.top + this.margin.bottom)
            .append('g')
            .attr('transform', `translate(${this.width/2 + this.margin.left},${this.height/2 + this.margin.top})`);

        this.handlers = {};
    }

    update(data) {
        this.data = data;  // 保存数据以供重绘使用
        this.svg.selectAll('*').remove();  // 清除所有元素

        const majors = ['工科类', '理科类', '文科类', '医学类', '艺术类'];
        const tools = ['ChatGPT', '文心一言', '通义千问', '豆包', 'Kimi', 'Deepseek'];
        const toolKeys = ['chatgpt', 'wenxin', 'qianwen', 'doubao', 'kimi', 'deepseek'];
        
        const color = d3.scaleOrdinal()
            .domain(majors)
            .range(['#4e79a7', '#f28e2c', '#59a14f', '#af7aa1', '#edc949']);

        // 绘制背景网格
        const angleSlice = Math.PI * 2 / tools.length;
        
        // 同心圆和刻度
        const levels = 5;
        for (let level = 1; level <= levels; level++) {
            const r = (this.radius * level) / levels;
            
            // 同心圆
            this.svg.append('circle')
                .attr('r', r)
                .style('fill', 'none')
                .style('stroke', '#ddd')
                .style('stroke-width', 1)
                .style('stroke-dasharray', '5,8');  
                
            // 刻度值
            const angle = Math.PI / 6; 
            this.svg.append('text')
                .attr('x', (r + 8) * Math.cos(angle - Math.PI/2))  
                .attr('y', (r + 8) * Math.sin(angle - Math.PI/2))
                .style('text-anchor', 'middle')
                .style('dominant-baseline', 'middle')
                .style('font-size', '12px')
                .style('fill', '#666')
                .style('font-weight', level === levels ? 'bold' : 'normal')
                .text(level);
        }

        // 轴线
        tools.forEach((tool, i) => {
            const angle = i * angleSlice;
            this.svg.append('line')
                .attr('x1', 0)
                .attr('y1', 0)
                .attr('x2', this.radius * Math.cos(angle - Math.PI/2))
                .attr('y2', this.radius * Math.sin(angle - Math.PI/2))
                .style('stroke', '#aaa')  
                .style('stroke-width', 1);
        });

        // 计算每个专业的雷达图面积
        const calculateArea = (points) => {
            let area = 0;
            for (let i = 0; i < points.length; i++) {
                const j = (i + 1) % points.length;
                area += points[i].x * points[j].y - points[j].x * points[i].y;
            }
            return Math.abs(area / 2);
        };

        // 处理数据并计算面积
        const dataWithArea = data.map(d => {
            const points = toolKeys.map((key, i) => ({
                x: this.radius * Math.cos(i * angleSlice - Math.PI/2) * d.scores[key]/5,
                y: this.radius * Math.sin(i * angleSlice - Math.PI/2) * d.scores[key]/5,
                score: d.scores[key],
                tool: tools[i]
            }));
            return {
                ...d,
                points,
                area: calculateArea(points)
            };
        });

        // 根据面积从大到小排序，这样面积小的会后绘制，显示在上层
        dataWithArea.sort((a, b) => b.area - a.area);

        // 数据点和路径
        dataWithArea.forEach(d => {
            const pathGroup = this.svg.append('g')
                .attr('class', 'radar-group')
                .attr('data-major', d.major);
            
            // 路径
            pathGroup.append('path')
                .datum(d.points)
                .attr('d', d3.line().x(d => d.x).y(d => d.y).curve(d3.curveLinearClosed))
                .attr('class', 'radar-area')
                .style('fill', color(d.major))
                .style('fill-opacity', 0.1)
                .style('stroke', color(d.major))
                .style('stroke-width', 1.5);

            // 数据点样式
            d.points.forEach(point => {
                // 添加阴影滤镜
                const filterId = `shadow-${d.major.replace(/\s+/g, '-')}`;
                this.svg.append('defs')
                    .append('filter')
                    .attr('id', filterId)
                    .append('feDropShadow')
                    .attr('dx', 0)
                    .attr('dy', 1)
                    .attr('stdDeviation', 1)
                    .attr('flood-opacity', 0.3);

                pathGroup.append('circle')
                    .attr('cx', point.x)
                    .attr('cy', point.y)
                    .attr('r', 3.5)
                    .style('fill', '#fff')
                    .style('stroke', color(d.major))
                    .style('stroke-width', 2)  
                    .style('filter', `url(#${filterId})`);  
            });
        });

        // 工具标签
        tools.forEach((tool, i) => {
            const angle = i * angleSlice - Math.PI/2;
            const basePadding = 20;
            const angleAdjustment = Math.abs(Math.cos(angle)) * 10;  
            const distance = this.radius + basePadding + angleAdjustment;
            
            this.svg.append('text')
                .attr('x', distance * Math.cos(angle))
                .attr('y', distance * Math.sin(angle))
                .attr('text-anchor', 'middle')
                .attr('dominant-baseline', 'middle')
                .style('font-size', '12px')  
                .style('fill', '#333')
                .text(tool);
        });

        // 添加鼠标交互
        const radarGroups = this.svg.selectAll('.radar-group');
        
        // 添加提示框
        const tooltip = d3.select('body')
            .append('div')
            .attr('class', 'radar-tooltip')
            .style('position', 'fixed')
            .style('visibility', 'hidden')
            .style('background-color', 'white')
            .style('padding', '5px 10px')
            .style('border', '1px solid #ddd')
            .style('border-radius', '3px')
            .style('font-size', '12px')
            .style('pointer-events', 'none')
            .style('box-shadow', '0 2px 4px rgba(0,0,0,0.1)')
            .style('z-index', '1000');

        // 鼠标交互
        radarGroups
            .on('mouseover', function(event) {
                const major = d3.select(this).attr('data-major');
                
                // 其他专业变暗
                radarGroups.each(function() {
                    if (d3.select(this).attr('data-major') !== major) {
                        d3.select(this).select('.radar-area')
                            .style('fill-opacity', 0.05)
                            .style('stroke-opacity', 0.1);
                        // 隐藏其他专业的评分点
                        d3.select(this).selectAll('circle')
                            .style('opacity', 0);
                    }
                });
                
                // 当前专业高亮
                d3.select(this).select('.radar-area')
                    .style('fill-opacity', 0.4)
                    .style('stroke-opacity', 1)
                    .style('stroke-width', 3);
                
                // 高亮对应的图例
                legend.selectAll('text')
                    .style('font-weight', d => d === major ? 'bold' : 'normal');
            })
            .on('mousemove', function(event) {
                const major = d3.select(this).attr('data-major');
                const majorData = data.find(d => d.major === major);
                
                tooltip
                    .style('visibility', 'visible')
                    .style('left', `${event.clientX + 10}px`)
                    .style('top', `${event.clientY - 10}px`)
                    .html(`<strong>${major}</strong><br>` + 
                          tools.map((tool, i) => 
                              `${tool}: ${majorData.scores[toolKeys[i]].toFixed(2)}`
                          ).join('<br>'));
            })
            .on('mouseout', function() {
                // 恢复所有样式
                radarGroups.selectAll('.radar-area')
                    .style('fill-opacity', 0.2)
                    .style('stroke-opacity', 1)
                    .style('stroke-width', 2);
                
                // 显示所有评分点
                radarGroups.selectAll('circle')
                    .style('opacity', 1);
                
                // 隐藏提示框
                tooltip.style('visibility', 'hidden');
                
                // 恢复图例样式
                legend.selectAll('text')
                    .style('font-weight', 'normal');
            });

        // 添加图例
        const legend = this.svg.append('g')
            .attr('class', 'legend')
            .attr('transform', `translate(${this.radius + 50}, ${-this.radius})`);

        majors.forEach((major, i) => {
            const legendRow = legend.append('g')
                .attr('transform', `translate(0, ${i * 20})`)
                .style('cursor', 'pointer')
                // 添加图例的鼠标交互
                .on('mouseover', function() {
                    // 触发对应雷达图区域的 mouseover 事件
                    radarGroups.each(function() {
                        if (d3.select(this).attr('data-major') === major) {
                            d3.select(this).dispatch('mouseover');
                        }
                    });
                })
                .on('mouseout', function() {
                    // 触发对应雷达图区域的 mouseout 事件
                    radarGroups.each(function() {
                        if (d3.select(this).attr('data-major') === major) {
                            d3.select(this).dispatch('mouseout');
                        }
                    });
                });

            legendRow.append('rect')
                .attr('width', 12)
                .attr('height', 12)
                .style('fill', color(major));

            legendRow.append('text')
                .attr('x', 20)
                .attr('y', 10)
                .style('font-size', '14px')
                .style('fill', '#333')
                .text(major);
        });

        // 标题
        this.svg.append('text')
            .attr('x', 0)
            .attr('y', -this.height/2 - 25)  
            .attr('text-anchor', 'middle')
            .style('font-size', '20px')
            .style('font-weight', 'bold')
            .text('各专业AI工具评分分布');
    }

    // 添加高亮方法
    highlight(major) {
        if (!this.svg || !this.data) return;
        
        if (!major) {
            this.update(this.data);  
            return;
        }
        
        const radarGroups = this.svg.selectAll('.radar-group');
        
        if (major) {
            radarGroups.each(function() {
                const group = d3.select(this);
                const currentMajor = group.attr('data-major');
                
                if (currentMajor !== major) {
                    // 其他专业变暗
                    group.select('.radar-area')
                        .style('fill-opacity', 0.05)
                        .style('stroke-opacity', 0.1);
                    // 只隐藏其他专业的评分点
                    group.selectAll('circle')
                        .style('opacity', 0);
                } else {
                    // 当前专业高亮
                    group.select('.radar-area')
                        .style('fill-opacity', 0.4)
                        .style('stroke-opacity', 1)
                        .style('stroke-width', 3);
                    // 保持当前专业的评分点显示
                    group.selectAll('circle')
                        .style('opacity', 1);
                }
            });
            
            // 高亮对应的图例
            this.svg.selectAll('.legend text')
                .style('font-weight', d => d === major ? 'bold' : 'normal');
        } else {
            // 恢复所有专业的显示
            radarGroups.selectAll('.radar-area')
                .style('fill-opacity', 0.2)
                .style('stroke-opacity', 1)
                .style('stroke-width', 2);
            
            // 显示所有评分点
            radarGroups.selectAll('circle')
                .style('opacity', 1);
            
            // 恢复图例样式
            this.svg.selectAll('.legend text')
                .style('font-weight', 'normal');
        }
    }
} 